package zhuzx.solution;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JOptionPane;

import org.zhuzx.util.GeneralUtil;
import org.zhuzx.util.JdbcUtil;
import zhuzx.generator.SqlTextParser;

public class EasyUiUtil {
	
	public static void main(String[] args) throws Exception {
		String inputValue = JOptionPane.showInputDialog("请输入sql语句或者表名：");
		Connection conn = JdbcUtil.getDbConn(null);
		inputValue = inputValue.trim();
		String[][] columns;
		if (inputValue.indexOf(" ") == -1) {
			columns = SqlTextParser.getMetaData(conn, inputValue);
		} else {
			columns = SqlTextParser.getColumns(conn, inputValue);
		}
		conn.close();
		
//		int option = JOptionPane.showConfirmDialog(null, "是否将字段名转化为驼峰格式？");
//		if (option == JOptionPane.YES_OPTION) {
//			for (int i=0; i<columns.length; i++) {
//				columns[i][0] = ClassCreator.convertUnderlineToCamelCased(columns[i][0]);
//			}
//		}
		
		createTableCode(columns);
	}

	public static void createTableCode(String[][] columns) {
		StringBuilder sb = new StringBuilder();
		for (String[] column : columns) {
			String name = column[0];
			if (name.equals("id") || name.equals("status") ||
					name.matches("^(create|update)_?time$")) continue;
			sb.append("<tr>\n\t<td>" + column[2] + "：" + "</td>\n\t<td>" +
					"<input id=\"" + name + "\" name=\"" + name + "\" " +
					"value=\"${" + name + "}\"\n\t\t" +
					"type=\"text\" ");
			switch (column[1]) {
				case "java.sql.Timestamp":
				case "java.sql.Date":
				case "java.sql.Time":
					sb.append("class=\"easyui-datebox\" editable=\"false\"");
					break;
				case "byte":
				case "int":
				case "long":
				case "java.math.BigInteger":
				case "float":
				case "double":
				case "java.math.BigDecimal":
					sb.append("class=\"easyui-numberbox\" data-options=\"precision:" + column[4] + "\"");
					break;
				default:
					sb.append("class=\"easyui-textbox\"");
					break;
			}
			sb.append("/></td>\n</tr>\n");
		}
		System.out.println(sb.toString());
	}

	public static void createDatagridString(String[][] columns) {
		String[] gridColumns = createDatagridColumns(columns);
		StringBuilder sb = new StringBuilder();
		for (String gc : gridColumns) {
			sb.append(gc + "\n");
		}
		sb.deleteCharAt(sb.length()-1);
		String gridStr = sb.toString();
		System.out.println(gridStr);
		String fullStr = "\"" + gridStr.replaceAll("\\n", "\" + \"\\\\n\" +\n\"") + "\"";
		String useableStr = "\"" + gridStr.replaceAll("\\n", "\" +\n\"") + "\"";
		String compressiveStr = gridStr.replaceAll("\\n", "").replaceAll("\\t", "");
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		Clipboard clipboard = toolkit.getSystemClipboard();
		StringSelection ss = new StringSelection(useableStr);
		clipboard.setContents(ss, null);
		System.out.println("----\n" + fullStr);
		System.out.println("----\n" + useableStr);
		System.out.println("----\n" + compressiveStr);
	}
	
	private static String[] createDatagridColumns(String[][] columns) {
		int length = "yyyy-MM-dd HH:mm:ss".length();
		String[] gridColumns = new String[columns.length];
		for (int i=0; i<columns.length; i++) {
			String[] colu = columns[i];
			colu[2] = (GeneralUtil.isBlank(colu[2])) ? colu[0] : colu[2];
			String row = "{field:'" + colu[0] + "', title:'" + colu[2] + "'";
			if (colu[0].equals("id")) {
				row += ", hidden:true";
			}
			if (colu[1].equals("java.sql.Timestamp")) {
				String func = ", formatter:function(value,row,index) {\n"
						+ "\treturn value.substring(0," + length + ");\n"
						+ "}";
				row += func;
			}
			String[] subitems = colu[2].replaceAll("-", "").split("[ :：,，;；.。()（）]");
			if (subitems.length >= 3) {
				Map<String,String> map = new HashMap<String,String>();
				String briefTitle = null;
				for (int j=0; j<subitems.length; j++) {
					if (subitems[j].length() == 0) continue;
					String num = subitems[j].substring(0, 1);
					try {
						Integer.parseInt(num);
						if (subitems[j].length() > 1) {
							map.put(num, subitems[j].substring(1));
						} else if (subitems[j].length() == 1){
							map.put(num, subitems[++j]);
						}
					} catch (NumberFormatException e) {
						if (j==0 && subitems[j].length()>=2) {
							briefTitle = subitems[j];
						}
						continue;
					}
				}
				if (briefTitle != null) {
					row = row.replaceFirst(" title:'[^']+'", " title:'"+briefTitle+"'");
				}
				if (map.size() >= 2) {
					System.out.println("----" + colu[2]);
					String func = ", formatter:function(value,row,index) {\n"
							+ "\tswitch (value) {\n";
					for (Map.Entry<String,String> entry : map.entrySet()) {
						func += "\t\tcase '" + entry.getKey() + "': "
								+ "return '" + entry.getValue() + "';\n";
					}
					func += "\t\tdefault: return value;\n\t}\n}";
					row += func;
				}
			}
			gridColumns[i] = row + "},";
		}
		String last = gridColumns[gridColumns.length-1];
		last = last.substring(0, last.length()-1);
		gridColumns[gridColumns.length-1] = last;
		return gridColumns;
	}

}
